package com.leetcode.algorithm.y22.m07.w2;

import com.leetcode.algorithm.common.ListNode;

/**
 * 2. 两数相加
 * 
 * https://leetcode.cn/problems/add-two-numbers/
 * 
 * @author jie.deng
 *
 */
class Question0002Solution02 {

	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		if (l1 == null) {
			return l2;
		} else if (l2 == null) {
			return l1;
		}
		ListNode sentinel = new ListNode();
		ListNode cur = sentinel;
		ListNode cur1 = l1;
		ListNode cur2 = l2;
		int carry = 0;
		while (cur1 != null || cur2 != null) {
			int sum = (cur1 == null ? 0 : cur1.val) + (cur2 == null ? 0 : cur2.val) + carry;
			carry = sum / 10;
			cur.next = new ListNode(sum % 10);
			cur = cur.next;
			cur1 = cur1 == null ? null : cur1.next;
			cur2 = cur2 == null ? null : cur2.next;
		}
		if (carry == 1) {
			cur.next = new ListNode(carry);
		}
		return sentinel.next;
	}

}